package com.okilo.online.app.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import com.okilo.online.app.R
import com.okilo.online.app.databinding.OkiloRootViewBinding
import com.okilo.online.app.tools.OkiloDensityUtil
import com.okilo.online.app.tools.OkiloTitleBarUtil
import com.okilo.online.app.tools.extensions.getColorRes
import com.okilo.online.app.tools.manager.OkiloTitleBarManager
import com.okilo.online.app.tools.manager.OkiloToastManager
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener


/**
 * BaseFragment
 * @Author wwdeng
 * @CreateTime: 2024/11/22 10:32
 * @Annotation：基类 Fragment
 */
abstract class OkiloBaseFmt: Fragment(), IOkiloBaseView {

    lateinit var rootViewBinding: OkiloRootViewBinding

    /** 管理器实例 */
    private lateinit var titleBarManager: OkiloTitleBarManager

    /* 配置变量 */
    private var isInterceptBack = false
    private var mActivity: Activity? = null

    /** 关联的BaseActivity */
    private var baseActivity: OkiloBaseAct? = null

    // 获取页面名称，子类必须实现
    protected abstract val pageName: String
    // 是否启用页面埋点（默认启用）
    protected open val enablePageTrack: Boolean = true

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = activity
        if (activity is OkiloBaseAct) {
            baseActivity = activity as OkiloBaseAct
        }
    }

    override fun onDetach() {
        super.onDetach()
        baseActivity = null
        mActivity = null
    }

    override fun getContext(): Context? {
        return mActivity
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootViewBinding = OkiloRootViewBinding.inflate(inflater)

        // 初始化管理器
        initializeManagers()

        // 设置状态栏padding
        val leftPadding = OkiloDensityUtil.dp2px(16f)
        val topPadding = OkiloDensityUtil.dp2px(10f)
        val bottomPadding = OkiloDensityUtil.dp2px(6f)
        rootViewBinding.rootTitleBar.setPadding(leftPadding, OkiloTitleBarUtil.getStatusBarHeight() + topPadding, leftPadding, bottomPadding)

        val contentView = createOkiloContentView(inflater)
        if (contentView != null){
            // 添加内容视图
            rootViewBinding.rootContainer.addView(
                contentView,
                FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            )
        }
        return rootViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if (savedInstanceState != null) {
            return
        }

        // 设置返回按钮监听
        setupBackButtonListener()

        // 默认隐藏TitleBar
        titleBarManager.setTitleBarVisibility(View.GONE)

        // 初始化视图组件
        initializeOkiloViews()
        setupOkiloEventListeners()
        loadOkiloData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理资源
        baseActivity?.hideOkiloLoading()
    }

    /**
     * 获取布局文件根视图
     */
    protected abstract fun createOkiloContentView(inflater: LayoutInflater): View?

    /**
     * 初始化 View 控件
     */
    protected abstract fun initializeOkiloViews()

    /**
     * 事件监听
     */
    protected abstract fun setupOkiloEventListeners()

    /**
     * 加载数据
     */
    protected abstract fun loadOkiloData()

    /**
     * 初始化所有管理器
     */
    private fun initializeManagers() {
        titleBarManager = OkiloTitleBarManager(rootViewBinding)
    }

    /**
     * 设置返回按钮点击监听器
     */
    private fun setupBackButtonListener() {
        rootViewBinding.rootBack.setOnClickListener(object : OkiloOnSingleClickListener() {
            override fun onSingleClick(v: View?) {
                onBackAction()
            }
        })
    }

    override fun showOkiloLoading() {
        if (isFragmentActive()) {
            showOkiloLoading(getString(R.string.okilo_loading))
        }
    }

    fun showOkiloLoading(msg: String = "") {
        if (isFragmentActive()) {
            baseActivity?.showOkiloLoading(msg)
        }
    }

    fun showOkiloLoading(isTouchOut: Boolean, isCancel: Boolean, msg: String = "") {
        if (isFragmentActive()) {
            baseActivity?.showOkiloLoading(isTouchOut = isTouchOut,isCancel = isCancel,msg = msg)
        }
    }

    override fun hideOkiloLoading() {
        if (isFragmentActive()) {
            baseActivity?.hideOkiloLoading()
        }
    }

    /**
     * toast
     * @param s
     */
    override fun showOkiloToast(s: String?) {
        if (isFragmentActive()) {
            baseActivity?.showOkiloToast(s) ?:
            OkiloToastManager.showShortText(requireContext(), s)
        }
    }

    /**
     * 页面跳转（不带参数）
     * @param T
     */
    open fun onIntent(T: Class<*>?) {
        if (isFragmentActive()) {
            baseActivity?.onIntent(T) ?:
            startActivity(Intent(requireContext(), T))
        }
    }

    /**
     * 页面跳转（带参数）
     * @param T
     * @param bundle
     */
    open fun onIntent(T: Class<*>?, bundle: Bundle?) {
        if (isFragmentActive()) {
            baseActivity?.onIntent(T, bundle) ?:
            startActivity(Intent(requireContext(), T).apply {
                bundle?.let { putExtras(it) }
            })
        }
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View) {
        if (isFragmentActive()) {
            baseActivity?.onHideSoftInput(v) ?:
            run {
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }
    }

    /**
     * 隐藏软键盘
     */
    fun onHideSoftInput() {
        if (isFragmentActive()) {
            baseActivity?.onHideSoftInput() ?:
            run {
                val view = requireActivity().currentFocus ?: requireActivity().window.decorView
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }
    }

    /* 显示键盘 */
    fun onShowSoftInput(v: View) {
        if (isFragmentActive()) {
            baseActivity?.onShowSoftInput(v) ?:
            run {
                v.requestFocus()
                val imm = requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(v, 0)
            }
        }
    }

    /* 是否拦截返回按钮 */
    fun isInterceptBack(isBackExit: Boolean) {
        isInterceptBack = isBackExit
    }

    /* 返回 */
    fun onBackAction() {
        if (!isInterceptBack) { // 不拦截，直接返回
            if (isFragmentActive()) {
                baseActivity?.onBackAction() ?: requireActivity().onBackPressed()
            }
        }
    }

    fun getColor(color: Int): Int {
        return requireContext().getColorRes(color)
    }

    /**
     * 检查Fragment是否处于活跃状态
     */
    private fun isFragmentActive(): Boolean {
        return isAdded && !isDetached && !isRemoving &&
                context != null &&
                activity != null && !requireActivity().isFinishing
    }

    /**
     * 获取关联的BaseActivity
     */
    protected fun getBaseActivity(): OkiloBaseAct? {
        return baseActivity
    }

    /**
     * 安全执行操作（避免Fragment状态异常）
     */
    protected fun safeRun(block: () -> Unit) {
        if (isFragmentActive()) {
            try {
                block()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 获取TitleBar管理器（用于链式调用）
     */
    protected fun getTitleBarManager(): OkiloTitleBarManager {
        return titleBarManager
    }

    /**
     * 设置右侧按钮点击监听器
     */
    protected fun setRightButtonClickListener(listener: View.OnClickListener) {
        titleBarManager.setRightButtonClickListener(listener)
    }

    /**
     * 设置返回按钮点击监听器（覆盖默认行为）
     */
    protected fun setBackButtonClickListener(listener: View.OnClickListener) {
        titleBarManager.setBackButtonClickListener(listener)
    }
}
